#include "login.h"
#include "ui_login.h"

Login::Login(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Login),
    manage(new ManageWindow),
    stu(new StuWindow)
{
    ui->setupUi(this);

    /* 设置图标 */
    setWindowIcon(QIcon(":/pic/lib.jpg"));

    /* 设置标题 */
    setWindowTitle("图书管理系统");

    appDir = QCoreApplication::applicationDirPath();

    connect(manage, &ManageWindow::close, this, &Login::closeManageWindow);     //管理员界面关闭，登录界面显示
    connect(stu, &StuWindow::close, this, &Login::closeStuWindow);              //学生界面关闭，登录界面显示
    connect(this, &Login::stulogin, stu, &StuWindow::getStuname);               //记录哪个学生登录
    connect(this, &Login::managelogin, manage, &ManageWindow::on_stuBtn_clicked);
    connect(this, &Login::managelogin, manage, &ManageWindow::on_bookBtn_clicked);
}

/* 点击登录按钮 */
void Login::on_loginBtn_clicked()
{
    if (ui->statusBox->currentText() == "学生")
    {
        if (isExist() == true)
        {
            this->hide();
            stu->show();
            emit stulogin(m_stuName);
        }
        else
        {
            QMessageBox::warning(this, "输入有误", "账号密码不正确");
            return;
        }
    }
    else if (ui->statusBox->currentText() == "管理员")
    {
        if (ui->le_id->text() == "1" && ui->le_password->text() == "1")
        {
            this->hide();
            manage->show();
        }
        else
        {
            QMessageBox::warning(this, "输入有误", "账号密码不正确");
            return;
        }
    }
}

/* 点击退出按钮 */
void Login::on_exitBtn_clicked()
{

}

/* 管理员界面关闭，登录界面显示 */
void Login::closeManageWindow()
{
    manage->hide();
    this->show();
    ui->le_id->clear();
    ui->le_password->clear();
}

/* 学生界面关闭，登录界面显示 */
void Login::closeStuWindow()
{
    stu->hide();
    this->show();
    ui->le_id->clear();
    ui->le_password->clear();
}

/* 判断学生账号是否存在 */
bool Login::isExist()
{
    QFile file(appDir + "/stuInfo.txt");
    if (file.exists() == false)
    {
        qDebug() << "创建stuInfo文件" << endl;
    }

    file.open(QIODevice::ReadOnly);

    char lineBuf[128] = {0};    //读取内容缓存区域
    while (file.atEnd() == false) // 逐行读取文件内容并计数
    {
        file.readLine(lineBuf, sizeof(lineBuf));    //读取一行文本并存入缓冲区
        QString data = lineBuf; //将char型的字符串转为QString型

        m_stuName = data.split("+")[0];
        QString id = data.split("+")[1];
        QString password = data.split("+")[2];
        if ((id == ui->le_id->text()) && (password == ui->le_password->text()))
        {
            return true;
        }
    }
    return false;
}

Login::~Login()
{
    delete ui;
}
